package com.sbw.wx.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;

/**
 * Desc: 文件工具类
 * @Date: 2021/6/27 9:07
 * @Author: Lee
 * 面朝大海  春暖花开
 * */
@Slf4j
public class FileUtil {

    /**
     * Desc: 获取指定路径图片的输入流
     * @Date: 2021/6/27 9:12
     * @Author: Lee
     * 面朝大海  春暖花开
     * */
    public static InputStream getFileInputStreams(String filePath) throws IOException {
        URL url = new URL(filePath);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(5 * 1000);
        InputStream inStream = conn.getInputStream();   // 通过输入流获取图片数据
        return inStream;
    }

    /**
     * Desc: 上传文件到微信服务器
     * @Date: 2021/6/27 15:04
     * @Author: Lee
     * 面朝大海  春暖花开
     * */
    public static String uploadFile2WxServer(String uploadUrl, String filePath){
        File tempFile = convertUrl2File(filePath);
//        String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
        log.info("上传文件到微信服务器，文件名称是:{}", tempFile.getName());
        DataInputStream inputStream = null;
        OutputStream outputStream = null;
        BufferedReader bufferedReader = null;
        try {
            // 定义请求数据类型
            String contentType = "application/octet-stream";
            // boundary就是request头和上传文件内容的分隔符
            String boundary = "---------------------------" + System.currentTimeMillis();
            HttpURLConnection connection = null;
            URL url = new URL(uploadUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(10000);
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setRequestMethod("POST");
            // 设置请求头信息
            connection.setRequestProperty("Connection", "Keep-Alive");
//            connection.setRequestProperty("Charset", "UTF-8");
            connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
            // 设置边界
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            // 获得输出流
            outputStream = new DataOutputStream(connection.getOutputStream());

            // 获取文件输入流
//            inputStream = new DataInputStream(getFileInputStreams(filePath));
            inputStream = new DataInputStream(new FileInputStream(tempFile));

            // 请求正文信息
            StringBuffer strBuf = new StringBuffer();
            strBuf.append("\r\n").append("--").append(boundary).append("\r\n");
            strBuf.append(
                    "Content-Disposition: form-data; name=\"media\"; filelength=\"" + tempFile.length() + "\"; filename=\"" + tempFile.getName() + "\" \r\n");
            strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
            outputStream.write(strBuf.toString().getBytes());

            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = inputStream.read(bufferOut)) != -1) {
                outputStream.write(bufferOut, 0, bytes);
            }
            byte[] endData = ("\r\n--" + boundary + "--\r\n").getBytes();
            outputStream.write(endData);
            outputStream.flush();

            // 读取返回数据
            StringBuffer stringBuffer = new StringBuffer();
            bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuffer.append(line).append("\n");
            }
            return stringBuffer.toString();
        } catch (IOException var0){
            log.error("上传文件到微信服务器异常，异常原因:{}", var0.getMessage());
            var0.printStackTrace();
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException var1){
                log.error("上传文件到微信服务器之后关闭资源异常，异常原因:{}", var1.getMessage());
            }
        }
        return "";
    }

    /**
     * Desc: 将一个url文件转为本地临时File对象
     * @Date: 2021/6/27 17:33
     * @Author: Lee
     * 面朝大海  春暖花开
     * */
    public static File convertUrl2File(String filePath){
        URL urlPath;
        File file = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;

        //对本地文件命名
        String fileSuffix = filePath.substring(filePath.lastIndexOf("."));
        try {
            file = File.createTempFile("tempFile", fileSuffix);
            // 下载
            urlPath = new URL(filePath);
            inputStream = urlPath.openStream();
            outputStream = new FileOutputStream(file);

            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != outputStream) {
                    outputStream.close();
                }
                if (null != inputStream) {
                    inputStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return file;
    }

}
